package com.orhon.smartcampus.modules.baseinfo.mutation;

import com.alibaba.fastjson.JSON;
import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.SchoolsDao;
import com.orhon.smartcampus.modules.base.entity.Schools;
import com.orhon.smartcampus.modules.baseinfo.dao.SemesterDao;
import com.orhon.smartcampus.modules.baseinfo.dao.TimetableDao;
import com.orhon.smartcampus.modules.baseinfo.entity.Semester;
import com.orhon.smartcampus.modules.baseinfo.entity.Timetable;
import com.orhon.smartcampus.modules.baseinfo.gqlInputModel.GQLTimetableInput;
import com.orhon.smartcampus.modules.baseinfo.inputMapper.TimetableInputMapper;
import com.orhon.smartcampus.modules.user.dao.TokenService;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;

@Component
public class AddTimetableMutation implements DataFetcher {


    @Autowired
    TimetableDao timetableDao;

    @Autowired
    SchoolsDao schoolsDao;

    @Autowired
    TokenService tokenService;

    /**
     * 添加作息表
     * editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {

        //String token = (String) SecurityUtils.getSubject().getPrincipal();
        String token = tokenService.getSystemToken();
        Long schoolId = JwtUtils.getSchoolId(token);

        GQLTimetableInput input = TimetableInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));

        Timetable timetable = null;

        if (input.getId() != null) {
            timetable = timetableDao.get(Timetable.class, input.getId());
            timetable.setUpdatedAt(new Date());
        } else {
            timetable = new Timetable();
            timetable.setCreatedAt(new Date());
        }

        if(input.getName() != null){

            timetable.setName(JSON.toJSONString(input.getName()));
        }
        if (schoolId != null) {
            timetable.setBaseSchoolsBySchoolId(schoolsDao.get(Schools.class, schoolId));
        }
        if(input.getIs_current() != null){

            timetable.setIsCurrent(input.getIs_current());
        }
        try {
            timetableDao.saveOrUpdate(timetable);
        } catch (Exception e) {
            return Result.error(500, "" + e);
        }
        return Result.ok();
    }
}

